package com.zhuhao.utils.httpclient;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

/**
 * okhttpclient
 * @Author haozhu7
 * @Date 2025/5/20 14:44
 **/
@Slf4j
public class OkHttpUtil {



    /**
     * 使用文本转语音服务
     * 网站地址：https://luvvoice.com/#myForm
     *
     * @throws IOException
     */
    @Test
    public void requestTts() throws IOException {
        String text = "哼，宝宝生气了，不想理你了";

        String url = "https://luvvoice.xyz/text_to_speech";
        OkHttpClient client = new OkHttpClient().newBuilder()
//                .connectTimeout(100, java.util.concurrent.TimeUnit.SECONDS)
//                .readTimeout(200, java.util.concurrent.TimeUnit.SECONDS)
//                .writeTimeout(150, java.util.concurrent.TimeUnit.SECONDS)
                .build();
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("text", text)
//                .addFormDataPart("language_code","zh-CN-XiaoyiNeural")
                .addFormDataPart("language_code", "zh-CN-XiaoxiaoNeural")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("origin", "https://luvvoice.com")
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Accept", "*/*")
                .addHeader("Host", "luvvoice.xyz")
                .addHeader("Connection", "keep-alive")
                .addHeader("Content-Type", "multipart/form-data; boundary=--------------------------024683934257995201139708")
                .build();
        Response response = client.newCall(request).execute();

        System.out.println(response.code());
        String bodyJosn = response.body().string();
        System.out.println(bodyJosn);

        String resultAudioUrl = (String) JSONUtil.parse(bodyJosn).getByPath("result_audio_url");
        System.out.println(resultAudioUrl);

        URL resultUrl = new URL(resultAudioUrl);
        File file = new File("src/121.mp3");
        FileUtils.copyURLToFile(resultUrl,file);

        System.out.println("下载完成");

    }

    /**
     * 根据map获取get请求参数
     *
     * @param queries
     * @return
     */
    public static StringBuffer getQueryString(String url, Map<String, String> queries) {
        StringBuffer sb = new StringBuffer(url);
        if (CollectionUtil.isNotEmpty(queries)) {
            boolean firstFlag = true;
            for (Map.Entry<String, String> entry : queries.entrySet()) {
                if (firstFlag) {
                    sb.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        return sb;
    }

    /**
     * 调用okhttp的newCall方法
     *
     * @param request
     * @return
     */
    private static String execNewCall(Request request) {
        Response response = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            log.info("ResponseCode={}", status);
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static String get(String url, Map<String, String> queries) {
        StringBuffer sb = getQueryString(url, queries);
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();
        return execNewCall(request);
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String postFormParams(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        return execNewCall(request);
    }


    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public static String postJsonParams(String url, String jsonParams, Map<String, String> headMap) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request.Builder builder = new Request.Builder();
        if (!CollectionUtil.isEmpty(headMap)) {
            for (String head : headMap.keySet()) {
                builder.header(head, headMap.get(head));
            }
        }

        Request request = builder
                .url(url)
                .post(requestBody)
                .build();
        return execNewCall(request);
    }

    /**
     * Post请求发送xml数据....
     * 参数一：请求Url
     * 参数二：请求的xmlString
     * 参数三：请求回调
     */
    public static String postXmlParams(String url, String xml) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return execNewCall(request);
    }
}
